<template>
  <div class="order-container">
    <!-- 1. 汇总卡片 -->
    <div class="summary-bar">
      <div class="summary-card">
        <div class="label">当日销售总金额</div>
        <div class="value">¥{{ todayAmount }}</div>
      </div>
      <div class="summary-card total">
        <div class="label">累计销售总金额</div>
        <div class="value">¥{{ totalAmount }}</div>
      </div>
    </div>

    <!-- 2. 查询区域 -->
    <div class="search-container">
      <el-select v-model="queryOrderStatus" placeholder="请选择订单状态" style="width: 200px">
        <el-option label="全部" value=""/>
        <el-option label="已完成" value="已完成"/>
      </el-select>
      <el-date-picker v-model="startTime" type="datetime" placeholder="开始时间" style="width: 220px"/>
      <el-date-picker v-model="endTime" type="datetime" placeholder="结束时间" style="width: 220px"/>
      <el-button @click="queryOrders" type="success" icon="Search">查询</el-button>
    </div>

    <!-- 3. 错误提示 -->
    <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>

    <!-- 4. 订单表格 -->
    <el-table :data="orderList" stripe empty-text="暂无数据" class="order-table">
      <el-table-column label="序号" type="index" width="60" align="center"/>
      <el-table-column label="订单内容" min-width="220">
        <template #default="{ row }">
          <div class="remark-bubble" v-html="(row.remark || '无')
            .replace(/null/g, '不添加小料')
            .replace(/;/g, '<br/>')"/>
        </template>
      </el-table-column>
      <el-table-column label="取餐码" width="120" align="center">
        <template #default="{ row }">
          <span v-if="row.pickupCode" class="pickup-code">{{ row.pickupCode }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态" width="120" align="center">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.orderStatus)" size="small">{{ row.orderStatus }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderTime" label="订单时间" width="180" align="center" :formatter="formatDateTime"/>
      <el-table-column prop="totalAmount" label="订单金额" width="120" align="center" :formatter="formatAmount" class-name="amount-col"/>
    </el-table>

    <!-- 5. 分页 -->
    <div class="pagination-container">
      <el-pagination background
                     v-model:current-page="pageContains.pageNum"
                     v-model:page-size="pageContains.pageSize"
                     :page-sizes="[10,20,30,50,100]"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="pageContains.total"
                     @size-change="handleSizeChange"
                     @current-change="handlePageChange"/>
    </div>

    <!-- 6. 详情弹窗 -->
    <el-dialog v-model="detailDialog" title="订单详情" width="500px">
      <el-form label-width="100px">
        <el-form-item label="订单 ID"><el-input :value="curOrder.id" disabled/></el-form-item>
        <el-form-item label="取餐码"><el-input :value="curOrder.pickupCode||'未生成'" disabled/></el-form-item>
        <el-form-item label="订单状态"><el-input :value="curOrder.orderStatus" disabled/></el-form-item>
        <el-form-item label="订单时间"><el-input :value="formatDateTime(curOrder,'orderTime')" disabled/></el-form-item>
        <el-form-item label="订单金额"><el-input :value="formatAmount(null,null,curOrder.totalAmount)" disabled/></el-form-item>
      </el-form>
      <template #footer><el-button @click="closeDetailDialog">关闭</el-button></template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import http from '@/axios/http'

/* -------------- 基础数据 -------------- */
const orderList = ref([])
const errorMessage = ref('')
const queryOrderStatus = ref('已完成')
const startTime = ref(null), endTime = ref(null)
const detailDialog = ref(false)
const curOrder = ref({})
const pageContains = reactive({ pageNum: 1, pageSize: 10, total: 0 })

/* -------------- 汇总金额 -------------- */
const todayAmount = computed(() => {
  const start = new Date(new Date().toLocaleDateString()).getTime()
  let sum = 0
  orderList.value.forEach(r => {
    if (new Date(r.orderTime).getTime() >= start) sum += Number(r.totalAmount || 0)
  })
  return sum.toFixed(2)
})
const totalAmount = computed(() => {
  return orderList.value.reduce((s, r) => s + Number(r.totalAmount || 0), 0).toFixed(2)
})

/* -------------- 生命周期 -------------- */
onMounted(() => queryOrders())

/* -------------- 接口 -------------- */
function queryOrders() {
  const param = {
    orderStatus: queryOrderStatus.value || null,
    startTime: startTime.value ? new Date(startTime.value).toISOString() : null,
    endTime: endTime.value ? new Date(endTime.value).toISOString() : null,
    pageNum: pageContains.pageNum,
    pageSize: pageContains.pageSize
  }
  http.post('/glsb/get_orders_by_status_and_time', param).then(res => {
    if (res.data.result === 'success') {
      Object.assign(pageContains, res.data.data)
      orderList.value = res.data.data.list
      ElMessage.success(`查询到 ${pageContains.total} 条${queryOrderStatus.value || '全部'}订单`)
    } else {
      errorMessage.value = res.data.error
      ElMessage.error(res.data.error)
    }
  }).catch(e => ElMessage.error('查询失败：' + e.message))
}

function getOrderInfo(id) {
  return http.post('/glsb/get_order_by_id', { orderId: id }).then(res => {
    if (res.data.result === 'success') {
      curOrder.value = { ...res.data.data, orderTime: res.data.data.orderTime ? new Date(res.data.data.orderTime) : null }
    } else {
      ElMessage.error(res.data.error)
    }
  })
}

/* -------------- 对话框 -------------- */
async function showDetailDialog(id) {
  await getOrderInfo(id)
  detailDialog.value = true
}
function closeDetailDialog() {
  detailDialog.value = false
  curOrder.value = {}
}

/* -------------- 分页 -------------- */
function handleSizeChange(val) {
  pageContains.pageSize = val
  pageContains.pageNum = 1
  queryOrders()
}
function handlePageChange(val) {
  pageContains.pageNum = val
  queryOrders()
}

/* -------------- 工具 -------------- */
function getStatusTagType(status) {
  switch (status) {
    case '制作中': return 'warning'
    case '待取餐': return 'primary'
    case '已完成': return 'success'
    default: return 'info'
  }
}
function formatDateTime(row, col, val) {
  const v = val || row[col]
  return v ? new Date(v).toLocaleString() : ''
}
function formatAmount(row, col, val) {
  const v = val || row?.[col] || 0
  return `¥${Number(v).toFixed(2)}`
}
</script>

<style scoped>
/* ---------- 基础变量：统一设计语言 ---------- */
:root {
  --primary: #409EFF;
  --success: #67C23A;
  --warning: #E6A23C;
  --danger: #F56C6C;
  --info: #909399;
  --bg: #f6f8fb;
  --card: #ffffff;
  --text-main: #303133;
  --text-light: #909399;
  --text-placeholder: #c0c4cc;
  --border: #ebeef5;
  --border-hover: #dcdfe6;
  --shadow-light: 0 2px 8px 0 rgba(0, 0, 0, 0.08);
  --shadow-medium: 0 4px 16px 0 rgba(0, 0, 0, 0.12);
  --radius-sm: 4px;
  --radius-md: 8px;
  --radius-lg: 12px;
  --spacing-xs: 8px;
  --spacing-sm: 12px;
  --spacing-md: 16px;
  --spacing-lg: 24px;
  --transition-fast: all 0.2s ease;
  --transition-normal: all 0.3s ease;
}

/* ---------- 容器基础样式 ---------- */
.order-container {
  padding: var(--spacing-lg);
  background: var(--bg);
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  color: var(--text-main);
}

/* ---------- 1. 汇总卡片：强化视觉焦点 ---------- */
.summary-bar {
  display: flex;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
}

.summary-card {
  flex: 1;
  padding: var(--spacing-lg);
  background: var(--card);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-light);
  text-align: center;
  transition: var(--transition-normal);
  border-top: 3px solid transparent;
}

/* 卡片顶部色条区分类型 */
.summary-card:not(.total) {
  border-top-color: var(--danger);
}
.summary-card.total {
  border-top-color: var(--success);
}

/*  hover 动效升级 */
.summary-card:hover {
  transform: translateY(-3px);
  box-shadow: var(--shadow-medium);
}

.summary-card .label {
  font-size: 14px;
  color: var(--text-light);
  margin-bottom: var(--spacing-xs);
  letter-spacing: 0.5px;
}

.summary-card .value {
  font-size: 28px;
  font-weight: 600;
  color: var(--danger);
  line-height: 1.2;
}

.summary-card.total .value {
  color: var(--success);
}

/* ---------- 2. 查询区域：优化布局与交互 ---------- */
.search-container {
  display: flex;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-lg);
  padding: var(--spacing-md);
  background: var(--card);
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-light);
  align-items: center;
  flex-wrap: wrap;
}

/* 输入框样式统一 */
:deep(.search-container .el-select),
:deep(.search-container .el-date-picker) {
  --el-input-focus-border-color: var(--primary);
  --el-input-hover-border-color: var(--primary);
  border-radius: var(--radius-sm);
}

/* 按钮样式升级 */
:deep(.search-container .el-button) {
  margin-left: auto;
  padding: 8px 20px;
  border-radius: var(--radius-sm);
  background: var(--primary);
  border-color: var(--primary);
  transition: var(--transition-fast);
}

:deep(.search-container .el-button:hover) {
  background: #337ecc;
  border-color: #337ecc;
  transform: translateY(-1px);
}

/* ---------- 3. 错误提示：增强警示性 ---------- */
.error-message {
  color: var(--danger);
  margin-bottom: var(--spacing-md);
  padding: var(--spacing-sm);
  background: #fff1f0;
  border-radius: var(--radius-sm);
  border-left: 4px solid var(--danger);
  text-align: left;
  font-size: 14px;
}

/* ---------- 4. 订单表格：优化可读性与交互 ---------- */
.order-table {
  width: 100%;
  background: var(--card);
  border-radius: var(--radius-md);
  overflow: hidden;
  box-shadow: var(--shadow-light);
  margin-bottom: var(--spacing-md);
}

/* 表头样式 */
:deep(.el-table__header-wrapper th) {
  background: #f8f9fa;
  color: var(--text-main);
  font-weight: 600;
  font-size: 14px;
  border-bottom: 1px solid var(--border);
}

/* 斑马纹表格 */
:deep(.el-table--striped .el-table__row--striped td) {
  background: #fafbfc;
}

/* 行 hover 与选中态 */
:deep(.el-table__body tr) {
  transition: var(--transition-fast);
}

:deep(.el-table__body tr:hover>td) {
  background: #f0f7ff !important;
  color: var(--primary);
}

:deep(.el-table__body tr.current-row>td) {
  background: #e6f7ff !important;
  color: var(--primary);
  font-weight: 500;
}

/* 单元格内边距 */
:deep(.el-table__cell) {
  padding: 12px 8px;
}

/* 金额列强调 */
:deep(.amount-col .cell) {
  color: var(--danger);
  font-weight: 600;
  font-size: 14px;
}

/* ---------- 5. 表格元素细节：精致化展示 ---------- */
/* 取餐码标签 */
.pickup-code {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 3px 12px;
  background: #fff2e8;
  color: #ff7d00;
  border-radius: 999px;
  font-weight: 600;
  font-size: 13px;
  letter-spacing: 1px;
}

/* 订单备注气泡 */
.remark-bubble {
  display: inline-block;
  max-width: 100%;
  padding: 8px 12px;
  background: #f0f7ff;
  border: 1px solid #c6e2ff;
  color: var(--primary);
  font-size: 13px;
  line-height: 1.6;
  border-radius: var(--radius-sm);
  word-break: break-all;
}

/* 状态标签优化 */
:deep(.el-table .el-tag) {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

/* ---------- 6. 分页区域：优化对齐与间距 ---------- */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: var(--spacing-md);
  padding: 8px 0;
}

:deep(.el-pagination) {
  --el-pagination-button-active-bg-color: var(--primary);
  --el-pagination-button-active-color: #fff;
  border-radius: var(--radius-sm);
}

:deep(.el-pagination__sizes .el-input .el-input__inner) {
  border-radius: var(--radius-sm);
}

/* ---------- 7. 详情弹窗：统一样式 ---------- */
:deep(.el-dialog) {
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-medium);
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid var(--border);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-sm);
}

:deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-main);
}

:deep(.el-dialog__body) {
  padding: 0 var(--spacing-lg) var(--spacing-lg);
}

:deep(.el-form-item) {
  margin-bottom: var(--spacing-md);
}

:deep(.el-form-item__label) {
  color: var(--text-light);
  font-size: 14px;
}

:deep(.el-form-item .el-input__inner) {
  border-radius: var(--radius-sm);
  background: #fafbfc;
  border-color: var(--border);
}

:deep(.el-dialog__footer) {
  border-top: 1px solid var(--border);
  padding: var(--spacing-md);
  margin-top: var(--spacing-sm);
}

:deep(.el-dialog__footer .el-button) {
  border-radius: var(--radius-sm);
  transition: var(--transition-fast);
}

:deep(.el-dialog__footer .el-button:hover) {
  transform: translateY(-1px);
}

/* ---------- 8. 响应式适配：移动端优化 ---------- */
@media (max-width: 768px) {
  .order-container {
    padding: var(--spacing-md);
  }

  /* 汇总卡片纵向排列 */
  .summary-bar {
    flex-direction: column;
    gap: var(--spacing-sm);
  }

  .summary-card .value {
    font-size: 24px;
  }

  /* 查询区纵向排列 */
  .search-container {
    flex-direction: column;
    gap: var(--spacing-xs);
    padding: var(--spacing-sm);
  }

  :deep(.search-container .el-select),
  :deep(.search-container .el-date-picker) {
    width: 100% !important;
  }

  :deep(.search-container .el-button) {
    margin-left: 0;
    width: 100%;
    margin-top: var(--spacing-xs);
  }

  /* 表格字号缩小 */
  :deep(.el-table__cell) {
    font-size: 13px;
    padding: 10px 4px;
  }

  /* 分页居中 */
  .pagination-container {
    justify-content: center;
  }

  /* 弹窗宽度调整 */
  :deep(.el-dialog) {
    width: 90% !important;
  }
}
</style>